package cn.asura.controller;

import cn.asura.pojo.Blog;
import cn.asura.pojo.BlogType;
import cn.asura.pojo.DateAndView;
import cn.asura.pojo.User;
import cn.asura.service.BlogService;
import cn.asura.service.BlogTypeService;
import cn.asura.service.BlogViewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Asura
 * @description
 * @createTime 2020-09-21 11:44
 */

@Controller
@RequestMapping("/blog")
public class BlogController {

    private static final int PAGE_SIZE = 2;

    private BlogService blogService;
    private BlogViewsService blogViewsService;
    private BlogTypeService blogTypeService;

    @Autowired
    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    @Autowired
    public void setBlogViewsService(BlogViewsService blogViewsService) {
        this.blogViewsService = blogViewsService;
    }

    @Autowired
    public void setBlogTypeService(BlogTypeService blogTypeService) {
        this.blogTypeService = blogTypeService;
    }

    @GetMapping("")
    public ModelAndView getBlogsByRule(String type) {
        List<Blog> blogs = blogService.getBlogsByRule(type);
        ModelAndView modelAndView = new ModelAndView("view/datas");
        modelAndView.addObject("datas", blogs);
        return modelAndView;
    }

    @RequestMapping("/queryList")
    public String queryList(String queryPageNum, String queryTitle, String blogTypeId, String startTime, String endTime, HttpServletRequest request, HttpSession session) {
        // 获取登录的用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");

        // 处理传入的数据
        int pageNum = 1;
        try {
            pageNum = Integer.parseInt(queryPageNum);
        } catch (NumberFormatException ignored) {
            System.out.println("忽略数字解析异常");
        }
        if (queryTitle == null) {
            queryTitle = "";
        }
        if ("0".equals(blogTypeId)) {
            blogTypeId = "";
        }

        // 获取登录用户的所有博客
        List<Blog> allBlogs = blogService.findAll(loginUser.getId(), "%" + queryTitle + "%", blogTypeId, startTime, endTime);

        // 获取用户当前页的博客
        List<Blog> thePageBlogList;

        try {
            thePageBlogList = allBlogs.subList((pageNum - 1) * PAGE_SIZE, pageNum * PAGE_SIZE);
        } catch (IndexOutOfBoundsException e) {
            try {
                thePageBlogList = allBlogs.subList((pageNum - 1) * PAGE_SIZE, allBlogs.size());
            } catch (IllegalArgumentException e1) {
                pageNum = 1;
                try {
                    thePageBlogList = allBlogs.subList(0, pageNum * PAGE_SIZE);
                } catch (IndexOutOfBoundsException e2) {
                    thePageBlogList = allBlogs.subList(0, allBlogs.size());
                }
            }
        } catch (IllegalArgumentException e) {
            pageNum = 1;
            thePageBlogList = allBlogs.subList(0, allBlogs.size());
        }

        System.out.println(thePageBlogList);

        Map<String, Object> queryInfoMap = new HashMap<>();
        queryInfoMap.put("pageNum", queryPageNum);
        queryInfoMap.put("queryTitle", queryTitle);
        queryInfoMap.put("blogTypeId", blogTypeId);
        queryInfoMap.put("startTime", startTime);
        queryInfoMap.put("endTime", endTime);
        HashMap<String, Object> pageInfoMap = new HashMap<>();
        pageInfoMap.put("results", thePageBlogList);
        pageInfoMap.put("totalPage",
                allBlogs.size() % PAGE_SIZE == 0 ? allBlogs.size() / PAGE_SIZE : allBlogs.size() / PAGE_SIZE + 1);
        pageInfoMap.put("pageNum", pageNum);
        //查询用户的所有博客类型
        List<BlogType> blogTypeList = blogTypeService.findAll(loginUser.getId(), "", "", "");
        // 存域
        request.setAttribute("pageInfo", pageInfoMap);
        request.setAttribute("queryInfo", queryInfoMap);
        request.setAttribute("types", blogTypeList);
        return "blog/index";
    }

    @GetMapping("/write")
    public String jumpToCreat(HttpSession session, HttpServletRequest request) {
        // 获取登录的用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        //查询用户的所有博客类型
        List<BlogType> blogTypeList = blogTypeService.findAll(loginUser.getId(), "", "", "");
        // 存域
        request.setAttribute("types", blogTypeList);
        return "blog/create";
    }

    @PostMapping("/write")
    @ResponseBody
    public String createBlog(Blog blog, HttpSession session, HttpServletResponse response) {
        // 获取登录的用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        // 设置响应json
        response.setContentType("application/json; charset=utf-8");
        // 保存响应的数据
        // 完善blog的信息
        blog.setInsertUser(loginUser.getNickName());
        blog.setUserId(loginUser.getId());
        // 调用service层保存博客
        boolean b = blogService.create(blog);
        return b ? "{\"success\":true,\"blogId\":\"" + blog.getId() + "\"}" : "{\"message\":\"博客发表失败\"}";
    }

    @RequestMapping("/info")
    public String blogInfo(int blogId, HttpServletRequest request) {
        //根据blogId去查blog
        Blog blog = blogService.findByBlogId(blogId);
        request.setAttribute("blogInfo", blog);
        return "blog/info";
    }

    @GetMapping("/update")
    public String jumpToUpdate(int blogId, HttpServletRequest request, HttpSession session) {
        //根据blogId查询指定的blog然后返回到update界面
        Blog blog = blogService.findByBlogId(blogId);
        request.setAttribute("blogInfo", blog);
        //查询该用户所有的博客类型
        // 获取登录的用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        //查询用户的所有博客类型
        List<BlogType> blogTypeList = blogTypeService.findAll(loginUser.getId(), "", "", "");
        request.setAttribute("types", blogTypeList);
        return "blog/update";
    }

    @PostMapping("/update")
    @ResponseBody
    public String update(Blog blog, HttpServletResponse response) {
        // 设置响应json
        response.setContentType("application/json; charset=utf-8");
        // 完善blog的信息
        // 调用service层保存博客
        boolean b = blogService.update(blog);
        return b ? "{\"success\":true,\"blogId\":\"" + blog.getId() + "\"}" : "{\"message\":\"博客修改失败\"}";
    }

    @GetMapping("/delete")
    @ResponseBody
    public String delete(int blogId, HttpServletResponse response) {
        // 设置响应json
        response.setContentType("application/json; charset=utf-8");
        boolean b = blogService.delete(blogId);
        return b ? "{\"success\":\"true\"}" : "{\"success\":\"false\",\"message\":\"删除失败\"}";
    }

    @GetMapping("/state")
    public String jumpToState(HttpSession session, HttpServletRequest request) {
        // 获取登录用户
        User loginUser = (User) session.getAttribute("_USER_MODEL");
        // 查询登录用户的博客近七天的浏览量
        List<DateAndView> list = blogViewsService.findViewsByUserId(loginUser.getId());
        list.sort(Comparator.comparing(DateAndView::getDate));
        request.setAttribute("list", list);
        System.out.println(list);
        return "blog/state";
    }
}
